﻿using Microsoft.Extensions.Caching.Memory;
using Newtonsoft.Json;
using SqlSugar;
using Zhao.Common.Helper;
using Zhao.IServer;
using Zhao.Models.DTO;
using Zhao.Models.Entity;
using Zhao.Repository.Base;
using Zhao.Repository.UnitOfWork;

namespace Zhao.Service
{

    /// <summary>
    /// 
    /// </summary>
    public class AreaServer : BaseService<Area>, IAreaServer
    {
        private readonly AreaCacheManager _cacheManager;

        public AreaServer(IBaseRepository<Area> baseDal, IUnitOfWork unitOfWork, IMemoryCache IMemoryCache,IMemoryCache memoryCache, AreaCacheManager areaCacheManager) : base(baseDal, unitOfWork)
        {
            _cacheManager = areaCacheManager;
        }

        public List<AreaDto> GetAreas(int parentId = 0)
        {
            // 从缓存获取数据（同步方法，避免异步开销）
            return _cacheManager.GetAreasByParentId(parentId);
        }

        //为什么使用同步 ：缓存操作（尤其是内存缓存）本身是高效且低延迟的，通常不需要异步执行

        /// <summary>
        /// 小程序使用的地区API
        /// </summary>
        /// <param name="cityName"></param>
        /// <param name="leven"></param>
        /// <returns></returns>
        public List<AreaDto> GetCity()
        {
            // 从缓存获取数据
            return _cacheManager.GetCity();
        }


        /// <summary>
        /// 验证省市区层级关系是否合法
        /// </summary>
        /// <param name="provinceId">省ID</param>
        /// <param name="cityId">市ID</param>
        /// <param name="zoneId">区ID</param>
        /// <returns>是否合法</returns>
        public  bool ValidateAreaHierarchy(int provinceId, int cityId, int zoneId)
        {
            // 从缓存获取所有地区数据（使用之前实现的缓存管理器）
            var allAreas = _cacheManager.GetAllAreas();

            // 从内存中查找省、市、区
            var province = allAreas.FirstOrDefault(x => x.Id == provinceId);
            var city = allAreas.FirstOrDefault(x => x.Id == cityId);
            var zone = allAreas.FirstOrDefault(x => x.Id == zoneId);

            // 验证层级关系
            return province != null
                && city != null
                && zone != null
                && city.ParentId == provinceId
                && zone.ParentId == cityId;
        }

    }

}
